package com.thinkgem.jeesite.frame.pm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.persistence.BaseConstants;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.frame.pm.dao.PmDataTreeItemMapper;
import com.thinkgem.jeesite.frame.pm.entity.PmDataTreeItem;
import com.thinkgem.jeesite.frame.pm.utils.PmCacheUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典Service
 *
 * @author kongxiangsheng
 * @version 2018-09-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PmDataTreeItemService extends ServiceImpl<PmDataTreeItemMapper, PmDataTreeItem> implements IService<PmDataTreeItem> {

    /**
     * 根据字典编码获取所有的字典项
     *
     * @param treeCode
     * @return
     */
    public List<PmDataTreeItem> getByTreeCode(String treeCode) {
        // 从缓存中获取所有的数据字典
        List<PmDataTreeItem> cacheDataTreeItems = PmCacheUtils.getDataTreeItems(treeCode);
        if (CollectionUtils.isNotEmpty(cacheDataTreeItems)) {
            return cacheDataTreeItems;
        }

        // 如果获取不到，则从数据库查询
        List<PmDataTreeItem> treeLists = this.baseMapper.selectByTreeCode(treeCode);
        if (CollectionUtils.isNotEmpty(treeLists)) {
            PmCacheUtils.putDataTreeItems(treeCode, treeLists);
            return treeLists;
        }

        // 数据库里也取不到，则返回空List
        return Lists.newArrayList();
    }

    /**
     * 得到树形节点的名称
     *
     * @param treeCode
     * @param treeItemId
     * @return
     */
    public String getTreeItemName(String treeCode, String treeItemId) {
        List<PmDataTreeItem> itemList = this.getByTreeCode(treeCode);
        for (PmDataTreeItem item : itemList) {
            if (treeItemId.equals(item.getId())) {
                return item.getName();
            }
        }
        return treeItemId;
    }

    /**
     * 得到树形节点的名称
     *
     * @param treeCode
     * @param treeItemId
     * @return
     */
    public PmDataTreeItem getDateTreeItem(String treeCode, String treeItemId) {
        List<PmDataTreeItem> itemList = this.getByTreeCode(treeCode);
        for (PmDataTreeItem item : itemList) {
            if (treeItemId.equals(item.getId())) {
                return item;
            }
        }
        return null;
    }

    /**
     * 根据父表主键查询
     *
     * @param pmDataTreeId
     * @return
     */
    public List<PmDataTreeItem> getByPmDataTreeId(String pmDataTreeId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(PmDataTreeItem.COL_DATA_TREE_ID, pmDataTreeId);
        return this.list(queryWrapper);
    }

    /**
     * 查询所有子节点
     *
     * @param id
     * @return
     */
    public List<PmDataTreeItem> selectChildren(String dataTreeId, String id) {
        if (StringUtils.isBlank(dataTreeId) || StringUtils.isBlank(id)) {
            return new ArrayList<PmDataTreeItem>();
        }
        String param = "," + id + ",";
        QueryWrapper queryWrapper = new QueryWrapper<PmDataTreeItem>();
        queryWrapper.eq(PmDataTreeItem.COL_DATA_TREE_ID, dataTreeId);
        queryWrapper.like(PmDataTreeItem.COL_PARENT_IDS, param);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 保存条目
     *
     * @param pmDataTreeItem
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveDataItem(PmDataTreeItem pmDataTreeItem) {
        if (StringUtils.isBlank(pmDataTreeItem.getId())) {
            return this.insertDataItem(pmDataTreeItem);
        }
        return this.updateDataItem(pmDataTreeItem);
    }

    /**
     * 插入条目
     *
     * @param pmDataTreeItem
     * @return
     */
    private boolean insertDataItem(PmDataTreeItem pmDataTreeItem) {
        // 设置parentId的默认值
        if (StringUtils.isBlank(pmDataTreeItem.getParentId())) {
            pmDataTreeItem.setParentId(BaseConstants.ROOT_TREE_ITEM_ID);
        }
        // 设置parentids的值
        if (BaseConstants.ROOT_TREE_ITEM_ID.equals(pmDataTreeItem.getParentId())) {
            pmDataTreeItem.setParentIds(BaseConstants.ROOT_TREE_ITEM_ID + ",");
        } else {
            PmDataTreeItem parentDataItem = this.baseMapper.selectById(pmDataTreeItem.getParentId());
            pmDataTreeItem.setParentIds(parentDataItem.getParentIds() + pmDataTreeItem.getParentId() + ",");
        }

        // 设置sort值
        this.autoGenSort(pmDataTreeItem);

        // 保存
        this.baseMapper.insert(pmDataTreeItem);
        return true;
    }

    /**
     * 更新条目
     *
     * @param pmDataTreeItem
     * @return
     */
    private boolean updateDataItem(PmDataTreeItem pmDataTreeItem) {
        // 获取修改前的parentIds，用于更新子节点的parentIds
        String oldParentIds = pmDataTreeItem.getParentIds();

        // 设置新的父节点串
        if (BaseConstants.ROOT_TREE_ITEM_ID.equals(pmDataTreeItem.getParentId())) {
            pmDataTreeItem.setParentIds(BaseConstants.ROOT_TREE_ITEM_ID + ",");
        } else {
            PmDataTreeItem parentDataItem = this.baseMapper.selectById(pmDataTreeItem.getParentId());
            pmDataTreeItem.setParentIds(parentDataItem.getParentIds() + pmDataTreeItem.getParentId() + ",");
        }
        // 设置sort值
        this.autoGenSort(pmDataTreeItem);

        // 保存或更新实体
        this.baseMapper.updateById(pmDataTreeItem);

        // 更新子节点 parentIds
        List<PmDataTreeItem> subDataItemList = this.selectChildren(pmDataTreeItem.getDataTreeId(), pmDataTreeItem.getId());
        for (PmDataTreeItem subDataItem : subDataItemList) {
            subDataItem.setParentIds(subDataItem.getParentIds().replace(oldParentIds, pmDataTreeItem.getParentIds()));
            this.baseMapper.updateById(subDataItem);
        }
        return true;
    }

    /**
     * 自动获取下一个sort字段的值
     *
     * @param pmDataTreeItem
     * @return
     */
    private void autoGenSort(PmDataTreeItem pmDataTreeItem) {
        if (null != pmDataTreeItem.getSort() && pmDataTreeItem.getSort() > 10) {
            return;
        }
        // 按照sort排序获取数据
        QueryWrapper queryWrapper = new QueryWrapper<PmDataTreeItem>();
        queryWrapper.select(PmDataTreeItem.COL_SORT);
        queryWrapper.eq(PmDataTreeItem.COL_DATA_TREE_ID, pmDataTreeItem.getDataTreeId());
        queryWrapper.eq(PmDataTreeItem.COL_PARENT_ID, pmDataTreeItem.getParentId());
        queryWrapper.orderByAsc(PmDataTreeItem.COL_SORT);
        queryWrapper.last("limit 1");
        List<PmDataTreeItem> list = this.baseMapper.selectList(queryWrapper);

        // 获取不到，则默认为10
        if (CollectionUtils.isEmpty(list)) {
            pmDataTreeItem.setSort(10);
        } else {
            pmDataTreeItem.setSort(list.get(0).getSort() + 10);
        }
    }

    /**
     * 删除条目及其子条目
     *
     * @param pmDataTreeItem
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteDataItem(PmDataTreeItem pmDataTreeItem) {
        int totalCount = 0;

        // 如果有子条目，则先删除子条目
        List<PmDataTreeItem> subDataItemList = this.selectChildren(pmDataTreeItem.getDataTreeId(), pmDataTreeItem.getId());
        for (PmDataTreeItem subDataItem : subDataItemList) {
            totalCount += this.baseMapper.deleteById(subDataItem.getId());
        }

        // 删除该条目
        totalCount += this.baseMapper.deleteById(pmDataTreeItem.getId());

        return totalCount;
    }

}